// 导入vue
import Vue from 'vue';
import Vuex from 'vuex';  //1导入vuex包
Vue.use(Vuex);//2 挂载至Vue 
let shopCar = JSON.parse(localStorage.getItem('shopCar')) || [];
var store = new Vuex.Store({ //3 创建 仓库
	state:{
		shopCar:shopCar//购物车
	},
	mutations:{
		//添加至购物车
		addCar(state,shopInfo){
			var flag = false;  //默认购物车中没有该商品
			state.shopCar.some(item =>{
				if(item.id === shopInfo.id){
					item.number += parseInt(shopInfo.number);
					flag = true;
					return true;
				}
			})	
			if(!flag){
				state.shopCar.push(shopInfo);		
			}
			localStorage.setItem('shopCar', JSON.stringify(state.shopCar));		
		},
		chageSelect(state,id){
			state.shopCar.forEach(item =>{
				if(parseInt(item.id) == parseInt(id)){
					item.seleted = !(item.seleted);
				}
			})
			localStorage.setItem('shopCar', JSON.stringify(state.shopCar));
		},
		removeCarGoods(state,id){
			state.shopCar.forEach((item,index) =>{
				if(parseInt(item.id)==parseInt(id)){
					state.shopCar.splice(index,1);
				}
			})
			localStorage.setItem('shopCar', JSON.stringify(state.shopCar));	
		}
			
	},
	getters:{
		getGoodsNumber(state){
			var count = 0;
			state.shopCar.forEach(item =>{
				count+=item.number;
			})
			return count;
		},
		getGoodsCount(state){
			var obj ={};
			state.shopCar.forEach(item =>{
				obj[`${item.id}`] = item.number;
			})
			return obj;
		},
		getGoodsSeleted(state){
			var o ={};
			state.shopCar.forEach(item =>{
				o[`${item.id}`] = item.seleted;
			})
			return o;
		},
		getGoodsCountAndPrice(state){
			var obj = {
				count:0,
				price:0
			}

			state.shopCar.forEach(item =>{
				if(item.seleted){
					obj.count+=item.number;
					obj.price+=item.price*item.number;
				}
			})

			return obj;
		}
	}
});
// 导入app组件
import app from './App.vue';
import router from './router.js';
import './lib/mui/css/mui.min.css';
import './lib/mui/css/icons-extra.css'
import MintUI from 'mint-ui'
Vue.use(MintUI);
import 'mint-ui/lib/style.css';
import VueResource from 'vue-resource';
// 2.2 安装 vue-resource
Vue.use(VueResource)
// 设置请求的根路径
Vue.http.options.root = 'http://www.liulongbin.top:3005';
// 配置vue-resource 的post请求头
Vue.http.headers.common['Authorization'] = 'Basic YXBpOnBhc3N3b3Jk';
//定义全局时间格式化过滤器
Vue.filter('dataFormat', function (input) {
	//定义全局的过滤器
	var d = new Date(input);
	var year = d.getFullYear().toString();  //获取年
	var month = (d.getMonth()+1).toString();
	var day = d.getDate().toString();
	var timer = d.getHours().toString();
	var min = d.getMinutes().toString();
	var sen = d.getSeconds().toString();
	var str = `
	${year}-${month.padStart(2,'0')}-${day.padStart(2,'0') }
	 ${timer.padStart(2,'0')}: ${min.padStart(2,'0')}:${sen.padStart(2,'0')}  `;
	// console.log(str);
	return str;
})
var vm = new Vue({
	el:'#app',
	render:c=>c(app),  //将app组件挂载至VM中
	// 挂载路由
	router,
	store //4把vuex的仓库挂载至VM示例，这样所有的组件都可以使用了
});


